package com.winton.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.winton.model.S_ITEM;
import com.winton.model.S_USER;
import com.winton.service.ItemService;
import com.winton.service.UserService;

@Controller
@RequestMapping("/admin")
public class AdminController {
	
	@Autowired
	ItemService itemService;
	
	@Autowired
	UserService userService;
	
	@RequestMapping("/userLogin")
	public String userLogin(HttpServletRequest request,RedirectAttributes attr, HttpSession session,S_USER user,Model model) {
		
		S_USER u = userService.userLogin(user);
		String result = "";		
		if(u==null) {					
			attr.addFlashAttribute("result","用户名或密码错误!");						
			result = "redirect:../login";			
		}else {
			session.setAttribute("user", u);
			index(request,session,model);
			result = "redirect:/admin/index";
		}
		return result;
	}
		
	@RequestMapping("/index")
	public String index(HttpServletRequest request, HttpSession session,Model model) {
						
		S_USER u = (S_USER) session.getAttribute("user");
				
		List<S_ITEM> list = itemService.getItemListByUserid(u.getId());		
		
		model.addAttribute("list", screenItem(list));
		
		return "admin/index";
	}
	
	@RequestMapping("/welcome")
	public ModelAndView welcome() {
		return new ModelAndView("admin/welcome", "message", "");
	}
	
	@RequestMapping("/queryUserList")
	public ModelAndView queryUserList(@RequestParam(value="pageon",defaultValue="1")int pageon,HttpServletRequest request, HttpSession session,S_USER user,Model model,ModelAndView mv) {
		
		model.addAttribute("user",user);
		mv.addAllObjects(userService.queryUserList(user,pageon));
		mv.setViewName("admin/admin-list");
		
		return mv;
	}
	
	@RequestMapping("/adminAdd")
	public String adminAdd(HttpServletRequest request, HttpSession session,S_USER user,Model model) {
										
		return "admin/admin-add";
	}
			
	@RequestMapping("/password")
	public String password(HttpServletRequest request, HttpSession session) {
		 								
		return "admin/admin-password-edit";
	}
	
	@RequestMapping("/userExit")
	public ModelAndView userExit(HttpServletRequest request, HttpSession session) {
		session.removeAttribute("user"); 								
		return new ModelAndView(new RedirectView("../login"));
	}
	
	@RequestMapping("/findUserByUserId")
	public String findUserByUserId(HttpServletRequest request, HttpSession session,S_USER user,Model model) {
					
		model.addAttribute("user", userService.findUserByUserId(user.getId()));
			
		return "admin/admin-update";
	}
	/**
	* @Description: TODO(用户栏目权限 管理) 
	* @param @param request
	* @param @param session
	* @param @param user
	* @param @param model
	* @param @return    入参
	* @return String    返回类型 
	* @date 2017年11月5日 上午9:44:26
	 */
	@RequestMapping("/userItemManage")
	public String userItemManage(HttpServletRequest request, HttpSession session,S_USER user,Model model) {
				
		model.addAttribute("user",userService.findUserByUserId(user.getId()));
		List<S_ITEM> list = itemService.getItemListByUserid(user.getId());
		List<S_ITEM> allitem = itemService.queryItemList(); 
		List<S_ITEM> l = new ArrayList<S_ITEM>();
				
		for (S_ITEM item : allitem) {						
			for (S_ITEM uitem : list) {				
				if(uitem.getId()==item.getId()) {
					item.setItemstate(1);					
				}
			}
			l.add(item);
		}						
		model.addAttribute("allitem",screenItem(l));
		return "admin/admin-accredit-manage";
	}
	@Transactional
	@ResponseBody
	@RequestMapping("/updateUserItem")
	public String updateUserItem(HttpServletRequest request, HttpSession session,int userid,String[] itemids,String[] childitemids,Model model) {
		
		int num = 0;
		if(itemids!=null || childitemids!=null) {
			String stritemid = String.join(",", itemids);
			String childitemid = String.join(",", childitemids);			
			StringBuilder strid = new StringBuilder();			
			strid.append(stritemid+","+childitemid);
			
			num = userService.updateUserItem(userid,strid.toString());						
		}else {
			num = userService.deleteUserItem(userid);
		}
		String obj = JSON.toJSONString(num, SerializerFeature.WriteMapNullValue);
		return obj;
	}
	
	@ResponseBody
	@RequestMapping("/updatePassword")
	public String updatePassword(HttpServletRequest request, HttpSession session,String password,String newpassword) {
		
		S_USER u = (S_USER) session.getAttribute("user");
		String obj = "";
		System.out.println("password===="+password);
		System.out.println("u.getPassword()===="+u.getPassword());
		System.out.println("========="+u.getPassword().equals(password));
		if(u.getPassword().equals(password)) {
			obj = JSON.toJSONString(userService.updatePassword(u.getId(),newpassword), SerializerFeature.WriteMapNullValue);
		}else {
			obj = JSON.toJSONString("原密码不正确！", SerializerFeature.WriteMapNullValue);
		}			 	
		return obj;
	}
	
	@ResponseBody
	@RequestMapping("/inserOrUpdatetUser")
	public String inserOrUpdatetUser(HttpServletRequest request, HttpSession session,S_USER user,ModelAndView mv) {
		
		String obj = (user.getId()!=0) ? userService.updateUser(user) : userService.insertUser(user);
		obj = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
		return obj;
	}
	
	@ResponseBody
	@RequestMapping("/updateUserDeleted")
	public String updateUserDeleted(HttpServletRequest request, HttpSession session,S_USER user,Model model) {
		
		String obj = JSON.toJSONString(userService.updateUserDeleted(user), SerializerFeature.WriteMapNullValue);
				
		return obj;
	}
	@Transactional
	@ResponseBody
	@RequestMapping("/deleteUserByUserId")
	public String deleteUserByUserId(HttpServletRequest request, HttpSession session,S_USER user,Model model) {
					
		String obj = JSON.toJSONString(userService.deleteUserByUserId(user.getId()), SerializerFeature.WriteMapNullValue);
		
		return obj;
	}
	
	/**
	* @Description: TODO(用户名 唯一校验) 
	* @param @param request
	* @param @param session
	* @param @param user
	* @param @return    入参
	* @return String    返回类型 
	* @date 2017年11月5日 上午9:56:39
	 */
	@ResponseBody
	@RequestMapping("/loginidVerify")
	public String loginidVerify(HttpServletRequest request, HttpSession session,S_USER user) {
				
		String obj = JSON.toJSONString(userService.loginidVerify(user.getLoginid(),user.getId()), SerializerFeature.WriteMapNullValue);
		
		return obj;
	}
	
	/**
	* @Description: TODO(区分一二级栏目  把二级栏目加入到对应的二级栏目下) 
	* @param @param list
	* @param @return    入参
	* @return List<S_ITEM>    返回类型 
	* @date 2017年11月5日 上午10:06:06
	 */
	private List<S_ITEM> screenItem(List<S_ITEM> list){
		
		for (S_ITEM item : list) {			
			List<S_ITEM> childList = new ArrayList<S_ITEM>();			
			for (S_ITEM childItem : list) {				
				if(item.getId()==childItem.getPid()) {
					childList.add(childItem);	
				}					
			}
			item.setChildItem(childList);
		}		
		List<S_ITEM> itemlist = new ArrayList<S_ITEM>();		
		for (S_ITEM s : list) {			
			if(s.getPid()==0) {
				itemlist.add(s);
			}			
		}		
		
		return itemlist;		
	}
	
	
}
